package com.itlaoqi.thread.juc;

import java.util.concurrent.BrokenBarrierException;
import java.util.concurrent.CyclicBarrier;
import java.util.concurrent.ExecutorService;
import java.util.concurrent.Executors;

/**
 * CyclicBarrier适用于多线程必须同时开始的场景
 */
public class CycleBarrierSample{
    private static CyclicBarrier cyclicBarrier = new CyclicBarrier(5);

    public static void main(String[] args) {
        ExecutorService threadPool = Executors.newCachedThreadPool();
        for (int i = 0; i < 5; i++) {
            final int index = 1;
            try {
                Thread.sleep(1000);
            } catch (InterruptedException e) {
                e.printStackTrace();
            }

            threadPool.execute(new Runnable() {
                @Override
                public void run() {
                    go();
                }
            });
        }
        threadPool.shutdown();
    }

    private static void go() {
        System.out.println(Thread.currentThread().getName() + ":准备就绪");
        try {
            cyclicBarrier.await();//设置屏障点，当累计5个线程准备好后，才运行后面的代码
            System.out.println(Thread.currentThread().getName() + ":开始运行");
        } catch (InterruptedException e) {
            e.printStackTrace();
        } catch (BrokenBarrierException e) {
            e.printStackTrace();
        }
    }
}






